import httpClient from './client';
import {FetchOptions, Response} from "@tauri-apps/plugin-http";
import {AuthUrlType, ContentType, ResponseType} from "./types.ts"
import {UserInfoType} from "../types/types.ts";
import cons from "../common/cons.ts";
httpClient.setBaseURL('http://localhost:1420/api');

httpClient.addRequestInterceptor({
    onRequest(config: FetchOptions): FetchOptions {
        config.headers = {
            ...config.headers,
        };
        if (config.authUrlType === AuthUrlType.AUTHORIZE){
            let userInfo:UserInfoType = JSON.parse(localStorage.getItem(cons.UserLocalStorageKey) || "{}");
            config.headers[cons.AuthAccount] = userInfo.account;
            config.headers[cons.AuthAccountToken] = userInfo.token;
        }
        config.cache = "no-cache";
        config.connectTimeout = 5000;
        config.proxy = {
            http:"http://localhost:3030"
        };
        if (config.contentType !=ContentType.NONE){
            config.headers['Content-Type'] = config.contentType;
        }

        config.headers['Accept'] = '*/*';
        config.headers['keepalive'] = true;
        return config;
    }
});

httpClient.addResponseInterceptor({
    onResponse<T>(response: Response<T>): Response<T> {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response;
    },
    onError(error: Error): void {
        console.error('HTTP request error:', error);
        throw error;
    }
});

export const get = async <T>(url: string) => {
    return httpClient.request<T>(url, { method: 'GET' })
}
export const post = async <T>(url: string,data:any,responseType:ResponseType = ResponseType.JSON,authUrlType:AuthUrlType = AuthUrlType.AUTHORIZE,contentType:string = ContentType.APPLICATION_JSON) => {
    return httpClient.request<T>(url, { method: 'POST', body:JSON.stringify(data), responseType: responseType,authUrlType:authUrlType,contentType:contentType });
}

export const postForm = async <T>(url: string,data:any,responseType:ResponseType = ResponseType.JSON,authUrlType:AuthUrlType = AuthUrlType.AUTHORIZE,contentType:string = ContentType.NONE) => {
    return httpClient.request<T>(url, { method: 'POST', body:data, responseType: responseType,authUrlType:authUrlType,contentType:contentType });
}
